import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Stack;

public class Tree {

    class Node {
        int data;
        Node left;
        Node right;
    }

    private Node root;

    /**
     * 向二叉树中插入节点
     *
     * @param data  插入节点的值
     * @param index 插入后此节点在完全二叉树中的位置（树的根节点为1）
     */
    public void insert(int data, int index) {
        Node node = new Node();
        node.data = data;
        if (index == 1) {
            root = node;
            return;
        }
        boolean left = index % 2 == 0;
        Node par = findNode(index / 2);
        if (left) {
            par.left = node;
        } else {
            par.right = node;
        }
    }

    /**
     * 返回查找结点的引用
     *
     * @param index 查找index位置的节点（树的根节点为1）
     * @return 返回查找节点
     */
    private Node findNode(int index) {
        Stack<Boolean> stack = new Stack<>();
        int temp = index;
        while (temp != 1) {
            stack.push(temp % 2 == 0);
            temp /= 2;
        }
        Node node = root;
        while (!stack.empty()) {
            boolean left = stack.pop();
            if (left) {
                node = node.left;
            } else {
                node = node.right;
            }
        }
        return node;
    }

    public void preOrder() {
        if (root == null) {
            return;
        }
        Stack<Node> s = new Stack<>();
        s.push(root);
        while (!s.empty()) {
            Node node = s.pop();
            System.out.print(node.data+" ");
            if (node.right != null) {
                s.push(node.right);
            }
            if (node.left != null) {
                s.push(node.left);
            }
        }
    }

    public void inOrder() {
        if (root == null) return;
        Stack<Node> s = new Stack<>();
        Node node = root;

        while (node != null || !s.empty()) {
            while (node != null) {
                s.push(node);
                node = node.left;
            }

            node = s.pop();
            System.out.print(node.data+" ");
            node = node.right;
        }
    }

    public void postOrder() {
        if (root == null) return;
        Stack<Node> s = new Stack<>();
        Node curr = root;
        Node pre = null;
        while (curr != null || !s.empty()) {
            while (curr != null) {
                s.push(curr);
                curr = curr.left;
            }
            curr = s.peek();
            if (curr.right == null || curr.right == pre) {
                System.out.print(curr.data+" ");
                pre = curr;
                s.pop();
                curr = null;
            } else {
                curr = curr.right;
            }
        }
    }

}